package cn.kgc.itrip.biz.service.impl;

import cn.kgc.itrip.beans.common.ResponseCode;
import cn.kgc.itrip.beans.common.ServerResponse;
import cn.kgc.itrip.beans.model.pojo.ItripComment;
import cn.kgc.itrip.beans.model.pojo.ItripHotelOrder;
import cn.kgc.itrip.beans.model.pojo.ItripImage;
import cn.kgc.itrip.beans.model.pojo.ItripUser;
import cn.kgc.itrip.beans.model.vo.*;
import cn.kgc.itrip.biz.service.itripCommentService;
import cn.kgc.itrip.mapper.itripAreaDic.ItripAreaDicMapper;
import cn.kgc.itrip.mapper.itripComment.ItripCommentMapper;
import cn.kgc.itrip.mapper.itripHotelOrder.ItripHotelOrderMapper;
import cn.kgc.itrip.mapper.itripImage.ItripImageMapper;
import cn.kgc.itrip.util.EmptyUtils;
import cn.kgc.itrip.util.Page;
import cn.kgc.itrip.util.RedisApi;
import cn.kgc.itrip.util.SystemConfig;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * @author 阿泽
 */
@Service("itripCommentService")
@Slf4j
public class itripCommentServiceimpl implements itripCommentService {
    @Resource
    private ItripCommentMapper itripCommentMapper;
    @Resource
    private ItripImageMapper itripImageMapper;
    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;
    @Resource
    private ItripAreaDicMapper itripAreaDicMapper;
    @Resource
    private RedisApi redisApi;

    @Resource
    private SystemConfig systemConfig;

    /**
     * 据酒店id查询酒店平均分
     *
     * @param hotelId
     * @return
     */
    @Override
    public ServerResponse gethotelscore(String hotelId) {
        if (hotelId == null) {
            log.error("获取酒店评分信息时发生了参数丢失");
            return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //总体评分、位置评分、设施评分、服务评分、卫生评分成功

        itriphotelscoreVo gethotelscore = itripCommentMapper.gethotelscore(Long.parseLong(hotelId));


        if (gethotelscore == null) {
            return ServerResponse.createByErrorMessage("获取评分失败");
        }
        return ServerResponse.createBySuccess(gethotelscore);
    }

    @Override
    public ServerResponse getcount(String hotelId) {
        if (hotelId == null) {
            log.error("根据酒店id查询评论数量时发生了参数丢失");
            return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //根据酒店id查询评论数量（全部评论、值得推荐、有待改善、有图片）
        ItripHotelCountVo itripHotelCountVo = new ItripHotelCountVo();

        Integer getallcomment = itripCommentMapper.getallcomment(Long.parseLong(hotelId));
        if (getallcomment == null) {
            return ServerResponse.createByErrorMessage("获取酒店总评论数失败");
        }
        Integer gethavingimg = itripCommentMapper.gethavingimg(Long.parseLong(hotelId));
        if (gethavingimg == null) {
            return ServerResponse.createByErrorMessage("获取酒店有图片数失败");
        }
        Integer getimprove = itripCommentMapper.getimprove(Long.parseLong(hotelId));
        if (getimprove == null) {
            return ServerResponse.createByErrorMessage("获取酒店有待改善数失败");
        }
        Integer getisok = itripCommentMapper.getisok(Long.parseLong(hotelId));

        if (getisok == null) {
            return ServerResponse.createByErrorMessage("获取酒店值得推荐数失败");
        }

        itripHotelCountVo.setAllcomment(getallcomment);
        itripHotelCountVo.setHavingimg(gethavingimg);
        itripHotelCountVo.setImprove(getimprove);
        itripHotelCountVo.setIsok(getisok);
        return ServerResponse.createBySuccess(itripHotelCountVo);
    }

    /**
     * 根据评论类型查询评论列表，并分页显示
     *
     * @param itripSearchCommentVO
     * @return
     */
/**
 * 全部评论：{"hotelId":10,"isHavingImg":-1,"isOk":-1,"pageSize":5,"pageNo":1}
 *
 * 有图片：{"hotelId":10,"isHavingImg":1,"isOk":-1,"pageSize":5,"pageNo":1}
 *
 * 值得推荐：{"hotelId":10,"isHavingImg":-1,"isOk":1,"pageSize":5,"pageNo":1}
 *
 * 有待改善：{"hotelId":10,"isHavingImg":-1,"isOk":0,"pageSize":5,"pageNo":1}
 */
    /**
     * 根据评论查询列表，并分页显示
     */
    @Override
    public ServerResponse getCommentList(ItripSearchCommentVo itripSearchCommentVO) throws Exception {
        if (itripSearchCommentVO.getIsOk() == -1) {
            itripSearchCommentVO.setIsOk(null);
        }
        if (itripSearchCommentVO.getIsHavingImg() == -1) {
            itripSearchCommentVO.setIsHavingImg(null);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("hotelId", itripSearchCommentVO.getHotelId());
        param.put("isHavimgImg", itripSearchCommentVO.getIsHavingImg());
        param.put("isOk", itripSearchCommentVO.getIsOk());

        //获取总条数
        Integer count = itripCommentMapper.getItripCommentCountByMap(param);
        Page page = new Page(itripSearchCommentVO.getPageNo(), itripSearchCommentVO.getPageSize(), count);
        param.put("pageNo", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<ItripCommentListVO> itripCommentListByMapWithDetail = itripCommentMapper.getcommentlist(param);
        page.setRows(itripCommentListByMapWithDetail);
        return ServerResponse.createBySuccess(page);
    }

    /**
     * 图片上传接口
     *
     * @param request
     * @return
     */
    //图片上传
    @Override
    public ServerResponse upload(HttpServletRequest request) throws Exception {

        List<String> hasError = new ArrayList<>();

        List<String> ouput = new ArrayList<>();

        //获取图片解析器
        CommonsMultipartResolver commonsMultipartResolver =
                new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断请求中是否带有文件上传
        if (commonsMultipartResolver.isMultipart(request)) {
            //处理文件上传   因为上传了文件延迟
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            //获取token
            String token = multipartRequest.getHeader("token");
            if (redisApi.exists(token)) {
                //获取文件的总数量
                int size = multipartRequest.getMultiFileMap().size();
                if (size >= 1 && size <= 4) {
                    //处理文件上传操作

                    //获取所有的文件   依次遍历
                    Iterator<String> fileNames = multipartRequest.getFileNames();

                    //根据token过去用户信息
                    ItripUser itripUser = JSONObject.parseObject(redisApi.get(token), ItripUser.class);
                    MultipartFile file = null;
                    while (fileNames.hasNext()) {
                        //进行文件上传
                        try {
                            //获取文件
                            file = multipartRequest.getFile(fileNames.next());

                            //根据具体文件 获取具体的文件名字
                            String originalFilename = file.getOriginalFilename();

                            //验证文件是否满足条件
                            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                            if (!originalFilename.equals(" ") && (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals(".png"))) {
                                //保存文件：文件名字不能使用原来的名字，自己生成【用户的id-系统时间毫秒数-随机数】
                                //设置新名字
                                String fileName = itripUser.getId() + "-" + System.currentTimeMillis() + "-" +
                                        (int) (Math.random() * 10000000) + suffix;

                                System.out.println(systemConfig.getFileUploadPath() + "路径");
                                //获取完成的保存路径【保存图片的位置】
                                String fullPath = systemConfig.getFileUploadPath() +
                                        File.separator + fileName;

                                //文件保存
                                file.transferTo(new File(fullPath));

                                //返回页面，图片的访问路径
                                ouput.add(systemConfig.getVisitImgUrl() + fileName);
                            } else {
                                hasError.add(originalFilename + "上传失败,类型不允许");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            hasError.add(file + "文件上传失败，请重新上传");
                        }
                    }
                    if (hasError.isEmpty()) {
                        return ServerResponse.createBySuccess(ouput);
                    } else {
                        return ServerResponse.createBySuccess(hasError.toString(), ouput);
                    }
                } else {
                    return ServerResponse.createByErrorMessage("文件数量不对");
                }
            } else {
                return ServerResponse.createByErrorMessage("token失效，请重新登录");
            }
        } else {
            return ServerResponse.createByErrorMessage("请求的内容不是上传文件的类型");
        }
    }

    //图片删除
    @Override
    public ServerResponse delpic(String imgName, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (redisApi.exists(token)) {
            //获取文件在服务器上的物理路径
            String fullpath = systemConfig.getFileUploadPath() + File.separator + imgName;
            File file = new File(fullpath);
            if (file.exists()) {
                //删除
                file.delete();
                return ServerResponse.createBySuccess("删除成功");
            } else {
                return ServerResponse.createByErrorMessage("删除失败，文件不存在");
            }
        } else {
            return ServerResponse.createByErrorMessage("token失效，重新登录");
        }
    }


    /**
     * 添加用户评论VO
     *
     * @param itripAddCommentVO
     * @return
     */
    //添加评论
    @Override
    public ServerResponse add(ItripAddCommentVO itripAddCommentVO, HttpServletRequest request) throws Exception {
        //判断token
        String token = request.getHeader("token");
        if (redisApi.exists(token)) {
            //封装数据
            ItripComment itripComment = new ItripComment();
            BeanUtils.copyProperties(itripAddCommentVO, itripComment);
            ItripUser user = JSONObject.parseObject(redisApi.get(token), ItripUser.class);
            itripComment.setCreationDate(new Date());
            itripComment.setCreatedBy(user.getId());
            itripComment.setUserId(user.getId());

            List<ItripImage> itripImages = new ArrayList<>();
            if (itripAddCommentVO.getIsHavingImg() == 1) {
                //说明本次上传有图片
                int i = 0;
                //封装图片信息
                for (ItripImage imag : itripAddCommentVO.getItripImages()) {
                    imag.setCreationDate(itripComment.getCreationDate());
                    imag.setPosition(++i);
                    imag.setCreatedBy(itripComment.getCreatedBy());
                    imag.setType("2");
                    itripImages.add(imag);
                }
            }
            //计算综合得分 ： （设施 +卫生+服务+位置）/ 4
            int sum = itripComment.getFacilitiesScore() + itripComment.getHygieneScore() +
                    itripComment.getPositionScore() + itripComment.getServiceScore();
            itripComment.setScore(sum / 4);
            //添加评论信息
            System.out.println("在这一步");
            itripCommentMapper.insertItripComment(itripComment);
            System.out.println("在下一步");
            //保存图片
            Long id = itripComment.getId();

            System.out.println(id + "值");
            if (EmptyUtils.isNotEmpty(itripImages)) {
                for (ItripImage imag : itripImages) {
                    imag.setTargetId(id);
                    itripImageMapper.insertItripImage(imag);
                }
            }
            //修改订单状态
            //修改订单的状态  改为已评论
            ItripHotelOrder order = new ItripHotelOrder();
            order.setOrderStatus(4);
            order.setModifyDate(itripComment.getCreationDate());
            order.setModifiedBy(itripComment.getCreatedBy());
            order.setId(itripComment.getOrderId());
            itripHotelOrderMapper.updateItripHotelOrder(order);
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByErrorMessage("token失效，请重新登录");
        }
    }

    @Override
    public ServerResponse gettraveltype() {

        List<ItripLabelDicVo> querytraveltypeList = itripAreaDicMapper.querytraveltype();

        if (querytraveltypeList == null) {
            return ServerResponse.createByErrorMessage("获取出游类型列表失败");
        }
        return ServerResponse.createBySuccess(querytraveltypeList);
    }

    /**
     * 根据targetId查询评论照片(type=2)
     *
     * @param targetId
     * @return
     */
    @Override
    public ServerResponse getimg(String targetId, String type) {

        List<ItripHotelImgVo> itripHotelImgVos = itripImageMapper.queryHotelImage(Long.parseLong(targetId), type);
        return ServerResponse.createBySuccess(itripHotelImgVos);
    }


}
